package com.zho.common.utility.db;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.zho.common.domain.db.PagingInfo;

import org.hibernate.Session;
import org.hibernate.Query;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;


@SuppressWarnings("serial")
public class SearchQueryTemplate implements Serializable {
	protected String queryString;
	protected String countQueryString;
	protected String groupBy;
	protected String orderColumn;
	protected PagingInfo pagingInfo;
	protected List<SearchItem> restrictions;
	
	public SearchQueryTemplate() {}
	
	public SearchQueryTemplate(String orderColumn, PagingInfo pagingInfo) {
		this.orderColumn = orderColumn;
		this.pagingInfo = pagingInfo;
	}
	public SearchQueryTemplate(String groupBy, String orderColumn, PagingInfo pagingInfo) {
		this.groupBy = groupBy;
		this.orderColumn = orderColumn;
		this.pagingInfo = pagingInfo;
	}
	
	public String getOrderColumn() {
		return orderColumn;
	}

	public String getQueryString() {
		return queryString;
	}

	public void setQueryString(String queryString) {
		this.queryString = queryString;
	}

	public String getCountQueryString() {
		return countQueryString;
	}

	public void setCountQueryString(String countQueryString) {
		this.countQueryString = countQueryString;
	}

	public void setOrderColumn(String orderColumn) {
		this.orderColumn = orderColumn;
	}

	public PagingInfo getPagingInfo() {
		return pagingInfo;
	}

	public void setPagingInfo(PagingInfo pagingInfo) {
		this.pagingInfo = pagingInfo;
	}

	public List<SearchItem> getRestrictions() {
		return restrictions;
	}

	public void setRestrictions(List<SearchItem> restrictions) {
		this.restrictions = restrictions;
	}
	
	/* Query */
	public Query getQuery(Session em) {
		return QueryBuilderUtils.getQuery(em, this.queryString, groupBy, orderColumn, restrictions);
	}
	
	public Query getCountQuery(Session em) {
		return QueryBuilderUtils.getQuery(em, this.countQueryString, groupBy, StringUtils.EMPTY, restrictions);
	}
	
	/* NamedQuery */
	public Query getNamedQuery(Session em) {
		return QueryBuilderUtils.getNamedQuery(em, this.queryString, restrictions);
	}
	
	public void addRestriction(SearchItem searchItem) {
		if (CollectionUtils.isEmpty(this.restrictions)) {
			this.restrictions = new ArrayList<SearchItem>();
		}
		this.restrictions.add(searchItem);
	}

	public String getGroupBy() {
		return groupBy;
	}

	public void setGroupBy(String groupBy) {
		this.groupBy = groupBy;
	}


}
